<template>
  <div class="table">
    <div class="content-common">
      <div class="search-top">
        <el-form :label-position="'top'" :inline="true" :model="query">
          <el-form-item label="测站名称">
            <el-input v-model="query.observer" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input v-model="query.deviceName" placeholder="设备名称"></el-input>
          </el-form-item>
          <el-form-item class="search-btn">
            <el-button
              class="table-btn-blur"
              @click="
                page.currentPage = 1;
                getData();
              "
              >查询</el-button
            >
          </el-form-item>
        </el-form>

        <div class="right-search">
          <el-button style="margin-right: 6px" type="primary" icon="download" @click="dcmb">设备清单导出</el-button>
          <el-button type="primary" class="table-btn-blur" @click="handleAdd()">新增</el-button>
        </div>
      </div>
      <el-table :data="tableData" border class="table-common" header-cell-class-name="table-header">
        <el-table-column prop="stnm" label="测站"></el-table-column>
        <el-table-column prop="deviceNo" label="设备编号"></el-table-column>
        <el-table-column prop="deviceName" label="设备名称 "></el-table-column>
        <el-table-column prop="value" label="价值（万元）"></el-table-column>
        <el-table-column prop="manager" label="管理人员"></el-table-column>
        <el-table-column prop="assetFlag" label="是否列入固定资产">
          <template #default="scope">
            <span v-show="scope.row.assetFlag == 0">否</span>

            <span v-show="scope.row.assetFlag == 1">是</span>
          </template>
        </el-table-column>
        <el-table-column prop="deviceStatus" label="状态">
          <template #default="scope">
            <span v-show="scope.row.deviceStatus == 1">在用</span>

            <span v-show="scope.row.deviceStatus == 2">停用</span>
            <span v-show="scope.row.deviceStatus == 3">损坏</span>
            <span v-show="scope.row.deviceStatus == 4">报废</span>
          </template>
        </el-table-column>
        <el-table-column prop="model" label="型号"></el-table-column>
        <el-table-column prop="purchaseTime" label="采购时间"></el-table-column>
        <el-table-column prop="num" label="数量"></el-table-column>

        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button type="success" class="table-btn-success" @click="handleEdit(scope.row)">编辑</el-button>

            <el-button type="danger" class="table-btn-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row type="flex" justify="end">
        <el-pagination background v-model:currentPage="page.currentPage" @current-change="getData" layout="prev,total, pager, next" :total="page.totalSize"> </el-pagination>
      </el-row>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="logTitle" v-model="editVisible" width="860px">
      <el-form ref="form" :rules="rules" :model="form" label-width="160px" label-position="top">
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="测站类型" prop="stType">
              <el-select @change="typeChange" style="width: 100%" v-model="form.stType" placeholder="请选择">
                <el-option label="坡面径流场" value="1"> </el-option>
                <el-option label="小流域控制站" value="2"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="测站" prop="stcd">
              <el-select style="width: 100%" v-model="form.stcd" filterable placeholder="请选择">
                <el-option v-show="item.stType == form.stType" v-for="item in stationData" :key="item.value" :label="item.stnm" :value="item.stcd"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="设备名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="设备编号" prop="deviceNo">
              <el-input v-model="form.deviceNo" placeholder="设备编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="价值（元）" prop="value">
              <el-input v-model="form.value" placeholder="价值（元）"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="管理人员" prop="manager">
              <el-input v-model="form.manager" placeholder="管理人员"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="采购时间" prop="purchaseTime">
              <el-date-picker style="width: 100%" v-model="form.purchaseTime" type="date" value-format="YYYY-MM-DD" placeholder="采购时间"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="数量" prop="num">
              <el-input v-model="form.num" placeholder="数量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="是否列入固定资产" prop="assetFlag">
              <el-select style="width: 100%" v-model="form.assetFlag" placeholder="请选择">
                <el-option label="否" value="0"> </el-option>
                <el-option label="是" value="1"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="状态" prop="deviceStatus">
              <el-select style="width: 100%" v-model="form.deviceStatus" filterable placeholder="请选择">
                <el-option label="在用" value="1"> </el-option>
                <el-option label="停用" value="2"> </el-option>
                <el-option label="损坏" value="3"> </el-option>
                <el-option label="报废" value="4"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="型号">
              <el-input v-model="form.model" placeholder="型号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="附件" prop="files">
              <uploadFiles :disabled="false" title="添加附件" @onImagesChange="handleGetUploadFiles($event, 'files')" ref="upload" :source="source"></uploadFiles>
            </el-form-item>
          </el-col>
          <el-col :span="7"> </el-col>
          <el-col :span="7"> </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import uploadFiles from '../tripManagement/uploadFiles.vue';
import {
  sysdictviewlistDictItem,
  reportfieldManageeditdoApprove,
  reportfieldManageeditrevokeRecord,
  reportfieldManageeditsubmitRecord,
  viewPageStationInfo,
  soilWatermanagedeviceRecordexportexportDeviceRecord,
  soilWatermanagedeviceRecordviewpageDeviceRecord,
  soilWatermanagedeviceRecordsavesaveDeviceRecord,
  soilWatermanagedeviceRecordremovedelDeviceRecord
} from '../../../api/index';
import moment from 'moment';
export default {
  name: 'zhengbianhanshuizhibeigaidu',
  components: { uploadFiles },
  data() {
    return {
      daoruUrl: globalVar.xiaoliuyubaseURL + '/soilWater/manage/file/create/filesUpload',
      headers: {
        Authorization: sessionStorage['token']
      },
      tijiaorule: {
        status: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      rules: {
        num: [{ required: true, message: '必填项', trigger: 'change' }],
        value: [{ required: true, message: '必填项', trigger: 'change' }],
        purchaseTime: [{ required: true, message: '必填项', trigger: 'change' }],
        deviceStatus: [{ required: true, message: '必填项', trigger: 'change' }],
        stcd: [{ required: true, message: '必填项', trigger: 'change' }],
        deviceName: [{ required: true, message: '必填项', trigger: 'change' }],
        deviceNo: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      shenpilog: false,
      globalUser: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      query: {
        year: globalyear
      },
      excelllog: false,
      formInline: {},
      tableData: [],

      editVisible: false,
      logTitle: '',
      pageTotal: 0,
      form: {},
      stationData: [],
      checkArr: [],
      tijiaoform: {
        status: 1
      },
      selnow: {},
      source: []
    };
  },
  created() {
    this.globalUser = globalUser;
    let that = this;
    this.query.year = globalyear;
    that.getData();
    this.getstationData();
    this.getchecktype();
  },
  methods: {
    // 上传列表
    handleGetUploadFiles(arr, type) {
      this.source = arr;
    },
    typeChange() {
      this.form.stcd = '';
    },
    dcmb() {
      // let that = this;
      // soilWatermanagedeviceRecordexportexportDeviceRecord()
      //   .then((res) => {
      //     const filename = '设备列表.xlsx';
      //     const blob = new Blob([res]);
      //     var downloadElement = document.createElement('a');
      //     var href = window.URL.createObjectURL(blob);
      //     downloadElement.href = href;
      //     downloadElement.download = filename;
      //     document.body.appendChild(downloadElement);
      //     downloadElement.click();
      //     document.body.removeChild(downloadElement);
      //     window.URL.revokeObjectURL(href);
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //   });
      let url = globalVar.xiaoliuyubaseURL + '/soilWater/manage/deviceRecord/export/exportDeviceRecord';
      var options = {
        url: url,
        method: 'post',
        responseType: 'blob',
        headers: {
          Authorization: sessionStorage.getItem('token')
        }
      };
      axios(options).then((res) => {
        if (res) {
          const link = document.createElement('a');
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }); //生成blob对象
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          const fileName = '设备列表';
          link.setAttribute('download', `${fileName}` + '.xlsx'); //下载的文件名以及文件格式
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          console.log('下载失败');
        }
      });
    },
    filesuccess(e) {
      if (e.code == 5000) {
        this.$message.error(e.object);
      } else {
        this.form.files = e.object;
        this.$message.success('操作成功');
      }
    },
    tomingxi(item) {
      this.$router.push({
        path: '/zhengbianjiangshuiguochengmingxi',
        query: item
      });
    },
    quedingtijiao() {
      this.tijiaoform.relatedNo = this.selnow.recordNo;
      let that = this;
      reportfieldManageeditdoApprove(that.tijiaoform)
        .then((e) => {
          that.$message.success('操作成功');
          that.shenpilog = false;
          that.getData();
        })
        .catch((e) => {
          console.log(err);
        });
    },
    getchecktype() {
      let that = this;
      sysdictviewlistDictItem({
        dictCode: 'ZD-000004'
      })
        .then((e) => {
          that.checkArr = e.object;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    shenpi(item) {
      this.tijiaoform.reviewer = item.reviewer;
      this.tijiaoform.relatedNo = item.recordNo;
      this.tijiaoform.approveType = 'R2';
      this.shenpilog = true;
      this.selnow = item;
    },
    getstationData() {
      let data = {
        currentPage: 1,
        pageSize: 1000
      };
      viewPageStationInfo(data).then((res) => {
        this.stationData = res.object.dataList;
      });
    },
    daorujiangyu() {
      let that = this;
      rainfallImportRainfallDaily(that.form)
        .then((e) => {
          console.log(e);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getData() {
      let data = {
        stType: systype,
        currentPage: this.page.currentPage,
        pageSize: 10,
        stcd: stationInfo.stcd,
        year: globalyear
      };
      soilWatermanagedeviceRecordviewpageDeviceRecord(data).then((res) => {
        this.tableData = res.object.dataList;

        this.page = res.object.page;
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          soilWatermanagedeviceRecordremovedelDeviceRecord({
            id: row.id
          }).then((e) => {
            this.$message.success('删除成功');
            this.getData();
          });
        })
        .catch(() => {});
    },
    chehui(row) {
      this.$confirm('确定撤回吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          reportfieldManageeditrevokeRecord({
            headNo: row.recordNo
          })
            .then((e) => {
              this.getData();
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },
    tijiao(row) {
      this.$confirm('确定提交吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          reportfieldManageeditsubmitRecord({
            headNo: row.recordNo
          })
            .then((e) => {
              this.getData();
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },
    // 编辑操作
    handleEdit(row) {
      let _this = this;
      row.year = String(row.year);
      this.form = row;
      // 设置初始数据
      if (_this.form.files) {
        const fileName = _this.form.fileName ? _this.form.fileName.split('#') : [];
        const source = _this.form.files.split(',').map((url, index) => {
          return {
            name: fileName[index],
            url: url,
            fileName: fileName[index].slice(0, fileName[index].lastIndexOf('.')),
            type: fileName[index].split('.')[fileName[index].split('.').length - 1]
          };
        });
        this.source = [...source];
      }
      this.logTitle = '编辑设备清单';

      this.editVisible = true;
    },
    handleAdd() {
      this.logTitle = '新增设备清单';
      this.form = {
        stType: systype,
        year: globalyear,
        status: 0,
        stcd: stationInfo.stcd
      };
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      let that = this;

      this.$refs['form'].validate((valid) => {
        if (valid) {
          let fileName = [];
          let files = [];
          this.source.forEach((item, index) => {
            fileName.push(item.name);
            files.push(item.url);
          });
          this.form.fileName = fileName.join('#');
          this.form.files = files.join(',');
          soilWatermanagedeviceRecordsavesaveDeviceRecord(that.form).then((e) => {
            this.editVisible = false;
            this.$message.success('操作成功');
            this.getData();
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.search-btn {
  margin-top: 30px;
  width: auto !important;
}
.table-btn-blur {
  background: #3f8cff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #fff !important;
}
.table-btn-success {
  background: #00b600 !important;
  border: 1px solid #00b600 !important;
  border-radius: 2px;
  color: #fff !important;
}
.table-btn-plain {
  background: #fff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #3f8cff !important;
  font-size: 14px;
}
.table-btn-warning {
  background: #ff842f !important;
  border: 1px solid #ff842f !important;
  border-radius: 2px;
  color: #fff !important;
}
.table-btn-delete {
  background: #ff544e !important;
  border: 1px solid #ff544e !important;
  border-radius: 2px;
  color: #fff !important;
}
</style>

